package com.zhouxiao.multithreading.线程执行顺序;

/**
 * @author 周小哥  gqzmy@163.com 2023/3/3 22:02
 * <p>
 * 需求：
 * 1、1号线程、2号线程、3号线程都要执行
 * 2、执行是有顺序的，1->2->3
 * <p>
 * 实现：使用线程的wait方法，使线程顺序执行
 */

public class ThreadWaitDemo {
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static Boolean t1_run = false;
    public static final Boolean t2_run = false;


    public static void main(String[] args) {

        Thread thread1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("1号线程");
                t1_run = true;
                lock1.notify();
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (lock1) {
                try {
                    if (!t1_run) {
                        System.out.println("1号线程还没有执行，2号线程要先等待");
                        lock1.wait();
                    }
                    synchronized (lock2) {
                        System.out.println("2号线程");
                        lock2.notify();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread thread3 = new Thread(() -> {
            synchronized (lock2) {
                try {
                    if (!t2_run) {
                        System.out.println("2号线程还没有执行，3号线程要先等待");
                        lock2.wait();
                    }
                    System.out.println("3号线程");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        System.out.println("开始。。。");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}
